package com.sddongyun.common;


import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
    public static String httpReader(String url, String code){
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);

        String result = null;
        try {
            client.executeMethod(method);
            int status = method.getStatusCode();
            if (status == HttpStatus.SC_OK) {
                result = method.getResponseBodyAsString();
            } else {
                logger.error("Method failed: " + method.getStatusLine());
            }
        } catch (HttpException e) {
            // 发生致命的异常，可能是协议不对或者返回的内容有问题
            logger.error("Please check your provided http address!");
        } catch (IOException e) {
            // 发生网络异常
           logger.error("发生网络异常！");
        } finally{
            // 释放连接
            if(method!=null)method.releaseConnection();
            method = null;
            client = null;
        }
        return result;
    }

    public static String httpGet(String url,String code) {
        String content = null;
        HttpClient httpClient = new HttpClient();
        //设置header
        httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT,"Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.2) Gecko/20090803 Fedora/3.5.2-2.fc11 Firefox/3.5.2");
        GetMethod method = new GetMethod(url);
        try {
            int statusCode = httpClient.executeMethod(method);
            System.out.println("httpClientUtils::statusCode="+statusCode);
            System.out.println(method.getStatusLine());
            content = new String(method.getResponseBody(), code);

        } catch (Exception e) {
            logger.error(url+"time out");
        } finally {
            if(method!=null)method.releaseConnection();
            method = null;
            httpClient = null;
        }
        return content;
    }

    public static String httpPost(String url, Map paramMap, String code) {

        String content = null;
        if (url == null || url.trim().length() == 0 || paramMap == null
                || paramMap.isEmpty())
            return null;
        HttpClient httpClient = new HttpClient();
        //设置header

        httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT,"Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.2) Gecko/20090803 Fedora/3.5.2-2.fc11 Firefox/3.5.2");//
        //httpClient.getParams().setParameter("Content-Type","application/x-www-form-urlencoded");
        //代理设置
        //httpClient.getHostConfiguration().setProxy("128.128.176.74", 808);

        PostMethod method = new PostMethod(url);
        Iterator it = paramMap.keySet().iterator();


        while (it.hasNext()) {
            String key = it.next() + "";
            Object o = paramMap.get(key);
            if (o != null && o instanceof String) {
                method.addParameter(new NameValuePair(key, o.toString()));
            }
            if (o != null && o instanceof String[]) {
                String[] s = (String[]) o;
                if (s != null)
                    for (int i = 0; i < s.length; i++) {
                        method.addParameter(new NameValuePair(key, s[i]));
                    }
            }
        }
        try {

            int statusCode = httpClient.executeMethod(method);

            System.out.println("httpClientUtils::statusCode="+statusCode);

            System.out.println(method.getStatusLine());
            content = new String(method.getResponseBody(), code);

        } catch (Exception e) {
            logger.error("time out");
            e.printStackTrace();
        } finally {
            if(method!=null)method.releaseConnection();
            method = null;
            httpClient = null;
        }
        return content;

    }

    public static String httpPost(String url, Map paramMap) {
        //编码：UTF-8
        return HttpClientUtil.httpPost(url, paramMap, "UTF-8");
    }
}
